package cn.usian.controller;

import cn.usian.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String path;

    @PostMapping("/upload")
    public R<String>upload(MultipartFile file) throws IOException {
        //1.获取文件
        String filename = file.getOriginalFilename();//3.jpg

        //2.截取文件名
        String extName = filename.substring(filename.lastIndexOf("."));
       String uuidFileName= UUID.randomUUID().toString()+extName;

        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        File targetFile = new File(dir, uuidFileName);

        file.transferTo(targetFile);

        return R.success(uuidFileName);
    }
    
    @GetMapping("/download")
    public  void  download(String name, HttpServletResponse response) throws IOException {
        //1.找到目标文件
        File targetFile = new File(path, name);
        FileInputStream fileInputStream = new FileInputStream(targetFile);
        ServletOutputStream outputStream = response.getOutputStream();

        byte[] buf= new byte[1024];
        int length=0;

        while ((length=fileInputStream.read(buf))!= -1){
            outputStream.write(buf,0,length);
        }
        fileInputStream.close();
    }
}
